from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Avg, Count
from .models import Movie, Rating

def home(request):
    # 简单推荐: 评分最高且评分人数较多的电影
    recommended_movies = Movie.objects.annotate(
        avg_rating=Avg('rating__rating'),
        num_ratings=Count('rating')
    ).filter(num_ratings__gte=50).order_by('-avg_rating')[:10]
    
    context = {
        'recommended_movies': recommended_movies
    }
    
    return render(request, 'yourapp/home.html', context)

@login_required
def user_recommendations(request):
    # 这里应该实现个性化推荐算法
    # 简单示例仅显示用户尚未评分的热门电影
    
    user = request.user
    rated_movies = Rating.objects.filter(user=user).values_list('movie_id', flat=True)
    
    recommended_movies = Movie.objects.exclude(
        movie_id__in=rated_movies
    ).annotate(
        avg_rating=Avg('rating__rating'),
        num_ratings=Count('rating')
    ).filter(num_ratings__gte=50).order_by('-avg_rating')[:10]
    
    context = {
        'recommended_movies': recommended_movies
    }
    
    return render(request, 'yourapp/recommendations.html', context) 